package org.budo.maven.plugin.assembly.mojo.util;

import java.io.File;
import java.io.InputStream;
import java.util.List;

import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.budo.support.lang.util.FileUtil;
import org.budo.support.lang.util.IoUtil;
import org.budo.support.lang.util.ListUtil;
import org.budo.support.lang.util.ProcessUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class MojoGitLogUtil {
    /**
     * 写入Git版本信息
     */
    public static void writeGitLogToConf(MavenProject project, Log log) {
        try {
            String gitLog = gitLog();

            String target = project.getBuild().getDirectory();
            File confDir = new File(target + File.separator + project.getArtifactId() + "-assembly" + File.separator + "conf");
            File to = new File(confDir, "git-log.txt");

            IoUtil.write(gitLog, to);
            log.info("#163 writing git-log.txt to " + FileUtil.getCanonicalPath(to));
        } catch (Throwable e) {
            log.error("#165 writeGitLog error, e=" + e, e);
        }
    }

    public static void writeGitLogToClasses(MavenProject project, Log log) {
        try {
            String gitLog = gitLog();

            String target = project.getBuild().getDirectory();
            File to = new File(target + File.separator + "classes", "git-log.properties");

            IoUtil.write(gitLog, to);
            log.info("#163 writing git-log.txt to " + FileUtil.getCanonicalPath(to));
        } catch (Throwable e) {
            log.error("#165 writeGitLog error, e=" + e, e);
        }
    }

    private static String gitLog() {
        List<String> command = ListUtil.toStringList("git", "log", "--graph", "-9"); // git log --graph -9

        try {
            InputStream inputStream = ProcessUtil.runCommand(command);
            String gitLog = IoUtil.toString(inputStream);
            return gitLog;
        } catch (Throwable e) {
            log.error("#62 gitLog error, e=" + e);
            return "git log error, " + e;
        }
    }
}